﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Joy.Erp.BasicArchives.Staff;
using Joy.Erp.BasicArchives.Suppliers;
using Joy.Erp.Ufida.Core;
using Microsoft.Extensions.Logging;

namespace Joy.Erp.Ufida.Suppliers
{
    public class SupplierSyncAppService : UfidaAppService, ISupplierSyncAppService
    {
        protected ISupplierRepository SupplierRepository => LazyServiceProvider.LazyGetRequiredService<ISupplierRepository>();
        protected ISupplierTypeRepository SupplierTypeRepository => LazyServiceProvider.LazyGetRequiredService<ISupplierTypeRepository>();
        protected IOperatorRepository OperatorRepository => LazyServiceProvider.LazyGetRequiredService<IOperatorRepository>();
        protected ISupplierUfidaAppService SupplierUfidaAppService => LazyServiceProvider.LazyGetRequiredService<ISupplierUfidaAppService>();

        public async Task<AnalysisDto> Analyze‌Async()
        {
            var analysisDto = new AnalysisDto();
            analysisDto.Id = typeof(Supplier).FullName;

            // 获取U9数据的ID列表
            var u9list = await SupplierUfidaAppService.GetAllAsync();
            var u9Ids = u9list.Select(x => x.ID.ToString()).ToHashSet();
            analysisDto.U9Count = u9Ids.Count;

            // 使用数据库查询优化，只查询需要的字段
            var pmcQuery = await SupplierRepository.GetQueryableAsync();

            // 获取PMC总数
            analysisDto.Count = await AsyncExecuter.CountAsync(pmcQuery.Where(x => !x.IsDeleted));

            // 获取已同步的SourceKey列表
            var syncedSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x => !x.IsDeleted && x.SourceType == SourceConfig.SourceType)
                    .Select(x => x.SourceKey)
            );

            // 使用 HashSet 快速计算已同步数量
            analysisDto.AsyncCount = syncedSourceKeys.Count(key => u9Ids.Contains(key));
            analysisDto.UnasyncCount = analysisDto.U9Count - analysisDto.AsyncCount;
            analysisDto.SelfCount = analysisDto.Count - analysisDto.AsyncCount;

            return analysisDto;
        }

        public async Task<List<long>> GetUnasyncIds()
        {
            // 获取U9的所有ID
            var u9list = await SupplierUfidaAppService.GetAllAsync();
            var u9Ids = u9list.Select(x => x.ID).ToList();

            // 使用数据库查询，只查询已同步的SourceKey
            var pmcQuery = await SupplierRepository.GetQueryableAsync();
            var syncedSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x => !x.IsDeleted && x.SourceType == SourceConfig.SourceType)
                    .Select(x => x.SourceKey)
            );

            // 使用 HashSet 优化查找性能，时间复杂度从 O(n²) 降到 O(n)
            var syncedSourceKeySet = new HashSet<string>(syncedSourceKeys);

            // 找出未同步的ID
            var unasyncIds = u9Ids
                .Where(id => !syncedSourceKeySet.Contains(id.ToString()))
                .ToList();

            return unasyncIds;
        }

        public async Task<int> CreateByIds‌Async(long[] ids)
        {
            if (ids == null || ids.Length == 0) return 0;

            var pmcQuery = await SupplierRepository.GetQueryableAsync();
            var idStrings = ids.Select(id => id.ToString()).ToList();
            var existingSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x =>
                        !x.IsDeleted
                        && x.SourceType == SourceConfig.SourceType
                        && idStrings.Contains(x.SourceKey)
                    )
                    .Select(x => x.SourceKey)
            );
            var existingSet = new HashSet<string>(existingSourceKeys);
            var needCreateIds = ids.Where(id => !existingSet.Contains(id.ToString())).ToList();
            if (needCreateIds.Count == 0) return ids.Length;

            Logger.LogInformation($"[批量同步-供应商] 开始处理 {needCreateIds.Count} 条供应商，总共 {ids.Length} 条（已存在 {existingSet.Count} 条）");

            var allU9DataDict = new Dictionary<long, SupplierUfidaDto>();
            foreach (var id in needCreateIds)
            {
                try
                {
                    var dto = await SupplierUfidaAppService.GetAsync(id);
                    if (dto != null)
                    {
                        allU9DataDict[id] = dto;
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-供应商] 获取U9数据失败，Id: {id}");
                }
            }

            if (allU9DataDict.Count == 0) return existingSet.Count;

            var typeIds = allU9DataDict.Values.Where(x => x.SupplierCategoryID.HasValue).Select(x => x.SupplierCategoryID.Value.ToString()).Distinct().ToList();
            var typeCacheDict = await BatchLoadSupplierTypes(typeIds);

            var operatorIds = allU9DataDict.Values.Where(x => x.OperatorsID.HasValue).Select(x => x.OperatorsID.Value.ToString()).Distinct().ToList();
            var operatorCacheDict = await BatchLoadOperators(operatorIds);

            var entities = new List<Supplier>();
            foreach (var kvp in allU9DataDict)
            {
                try
                {
                    var entity = GetEntity(kvp.Value, typeCacheDict, operatorCacheDict);
                    if (entity != null)
                    {
                        entities.Add(entity);
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-供应商] 创建实体失败，Id: {kvp.Key}");
                }
            }

            var successCount = 0;
            if (entities.Count > 0)
            {
                using (var uow = UnitOfWorkManager.Begin(new Volo.Abp.Uow.AbpUnitOfWorkOptions(), requiresNew: true))
                {
                    try
                    {
                        await SupplierRepository.BulkInsertAsync(entities, autoSave: false);
                        await uow.CompleteAsync();
                        successCount = entities.Count;
                    }
                    catch (Exception ex)
                    {
                        Logger.LogWarning(ex, $"[批量同步-供应商] 批量插入失败，{ex.Message}");
                    }
                }
            }

            Logger.LogInformation($"[批量同步-供应商] 完成！成功创建 {successCount} 条，已存在 {existingSet.Count} 条，总计 {successCount + existingSet.Count} 条");

            return successCount + existingSet.Count;
        }

        public async Task<List<long>> GetSyncedIds()
        {
            var pmcQuery = await SupplierRepository.GetQueryableAsync();
            var syncedSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x => !x.IsDeleted && x.SourceType == SourceConfig.SourceType)
                    .Select(x => x.SourceKey)
            );
            return syncedSourceKeys
                .Select(
                    key => long.TryParse(key, out var parsedId) ? (long?)parsedId : null
                )
                .Where(id => id.HasValue)
                .Select(id => id.Value)
                .ToList();
        }

        public async Task<int> UpdateByIds‌Async(long[] ids)
        {
            if (ids == null || ids.Length == 0) return 0;

            Logger.LogInformation($"[批量同步-供应商] 开始处理 {ids.Length} 条供应商更新/删除");

            var pmcQuery = await SupplierRepository.GetQueryableAsync();
            var idStrings = ids.Select(id => id.ToString()).ToList();
            var existingEntities = await AsyncExecuter.ToListAsync(
                pmcQuery.Where(x =>
                    !x.IsDeleted
                    && x.SourceType == SourceConfig.SourceType
                    && idStrings.Contains(x.SourceKey)
                )
            );
            if (existingEntities.Count == 0)
            {
                Logger.LogWarning($"[批量同步-供应商] 没有找到需要更新或删除的记录");
                return 0;
            }
            var entityDict = existingEntities.ToDictionary(x => x.SourceKey, x => x);

            var allU9DataDict = new Dictionary<long, SupplierUfidaDto>();
            foreach (var id in ids)
            {
                var key = id.ToString();
                if (!entityDict.ContainsKey(key)) continue;

                try
                {
                    var dto = await SupplierUfidaAppService.GetAsync(id);
                    if (dto != null)
                    {
                        allU9DataDict[id] = dto;
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-供应商] 获取U9数据失败，Id: {id}");
                }
            }

            var typeIds = allU9DataDict.Values.Where(x => x.SupplierCategoryID.HasValue).Select(x => x.SupplierCategoryID.Value.ToString()).Distinct().ToList();
            var typeCacheDict = await BatchLoadSupplierTypes(typeIds);

            var operatorIds = allU9DataDict.Values.Where(x => x.OperatorsID.HasValue).Select(x => x.OperatorsID.Value.ToString()).Distinct().ToList();
            var operatorCacheDict = await BatchLoadOperators(operatorIds);

            var entitiesToUpdate = new List<Supplier>();
            var entitiesToDelete = new List<Supplier>();
            foreach (var id in ids)
            {
                if (!entityDict.TryGetValue(id.ToString(), out var entity)) continue;

                try
                {
                    if (!allU9DataDict.TryGetValue(id, out var u9Data))
                    {
                        entitiesToDelete.Add(entity);
                        continue;
                    }

                    entity.SupplierTypeId = null;
                    if (u9Data.SupplierCategoryID.HasValue && typeCacheDict.TryGetValue(u9Data.SupplierCategoryID.Value.ToString(), out var typeDto))
                    {
                        entity.SupplierTypeId = typeDto.Id;
                    }
                    entity.Code = u9Data.Code;
                    entity.Name = u9Data.Name;
                    entity.ShortName = u9Data.ShortName;
                    entity.Contact = u9Data.Contact;
                    entity.Phone = u9Data.Phone;
                    entity.Address = u9Data.Address;
                    entity.SourceCreatedOn = u9Data.CreatedOn;
                    entity.OperatorId = null;
                    if (u9Data.OperatorsID.HasValue && operatorCacheDict.TryGetValue(u9Data.OperatorsID.Value.ToString(), out var operatorDto))
                    {
                        entity.OperatorId = operatorDto.Id;
                    }

                    entitiesToUpdate.Add(entity);
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-供应商] 处理实体失败，Id: {id}");
                }
            }

            if (entitiesToUpdate.Count == 0 && entitiesToDelete.Count == 0)
            {
                Logger.LogInformation($"[批量同步-供应商] 无需更新或删除记录");
                return 0;
            }

            var updateCount = 0;
            var deleteCount = 0;
            using (var uow = UnitOfWorkManager.Begin(new Volo.Abp.Uow.AbpUnitOfWorkOptions(), requiresNew: true))
            {
                try
                {
                    if (entitiesToUpdate.Count > 0)
                    {
                        await SupplierRepository.BulkUpdateAsync(entitiesToUpdate, autoSave: false);
                        updateCount = entitiesToUpdate.Count;
                    }

                    if (entitiesToDelete.Count > 0)
                    {
                        await SupplierRepository.BulkDeleteAsync(entitiesToDelete, autoSave: false);
                        deleteCount = entitiesToDelete.Count;
                    }

                    await uow.CompleteAsync();
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-供应商] 批量更新/删除失败，{ex.Message}");
                }
            }

            Logger.LogInformation($"[批量同步-供应商] 完成！成功更新 {updateCount} 条，删除 {deleteCount} 条");
            return updateCount + deleteCount;
        }

        private Supplier GetEntity(
            SupplierUfidaDto dto,
            Dictionary<string, SupplierTypeDto> typeCacheDict,
            Dictionary<string, OperatorDto> operatorCacheDict
        )
        {
            Guid? supplierTypeId = null;
            if (dto.SupplierCategoryID.HasValue && typeCacheDict.TryGetValue(dto.SupplierCategoryID.Value.ToString(), out var typeDto))
            {
                supplierTypeId = typeDto.Id;
            }
            var entity = new Supplier
            {
                SourceType = SourceConfig.SourceType,
                SourceKey = dto.ID.ToString(),
                SourceCreatedOn = dto.CreatedOn,
                SupplierTypeId = supplierTypeId,
                Code = dto.Code,
                Name = dto.Name,
                ShortName = dto.ShortName,
                Contact = dto.Contact,
                Phone = dto.Phone,
                Address = dto.Address,
                OperatorId = null,
                Enabled = true,
                CreationTime = Clock.Now,
                CreatorId = CurrentUser.Id,
                TenantId = CurrentTenant.Id,
            };
            if (dto.OperatorsID.HasValue && operatorCacheDict.TryGetValue(dto.OperatorsID.Value.ToString(), out var operatorDto))
            {
                entity.OperatorId = operatorDto.Id;
            }
            entity.SetId(GuidGenerator.Create());
            return entity;
        }

        private async Task<Dictionary<string, SupplierTypeDto>> BatchLoadSupplierTypes(List<string> sourceKeys)
        {
            if (sourceKeys == null || sourceKeys.Count == 0) return new Dictionary<string, SupplierTypeDto>();

            var query = await SupplierTypeRepository.GetQueryableAsync();
            var items = await AsyncExecuter.ToListAsync(
                query.Where(x =>
                    sourceKeys.Contains(x.SourceKey) && x.SourceType == SourceConfig.SourceType
                )
            );
            return items.ToDictionary(
                x => x.SourceKey,
                x => ObjectMapper.Map<SupplierType, SupplierTypeDto>(x)
            );
        }

        private async Task<Dictionary<string, OperatorDto>> BatchLoadOperators(List<string> sourceKeys)
        {
            if (sourceKeys == null || sourceKeys.Count == 0) return new Dictionary<string, OperatorDto>();

            var query = await OperatorRepository.GetQueryableAsync();
            var items = await AsyncExecuter.ToListAsync(
                query.Where(x =>
                    sourceKeys.Contains(x.SourceKey) && x.SourceType == SourceConfig.SourceType
                )
            );
            return items.ToDictionary(
                x => x.SourceKey,
                x => ObjectMapper.Map<Operator, OperatorDto>(x)
            );
        }
    }
}
